package com.myhexin.demo.plugin.message;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangzhonglv@myhexin.com
 * @date 2025/7/13
 */
public class PluginLoader {

    public static MessagePlugin loadPlugin(String jarPath, String className) throws Exception {
        File jarFile = new File(jarPath);
        if (!jarFile.exists()) {
            throw new IllegalArgumentException("Plugin JAR not found: " + jarPath);
        }

        URL[] urls = { jarFile.toURI().toURL() };
        try (URLClassLoader loader = new URLClassLoader(urls, MessagePlugin.class.getClassLoader())) {
            Class<?> clazz = loader.loadClass(className);
            Object instance = clazz.getDeclaredConstructor().newInstance();
            if (!(instance instanceof MessagePlugin)) {
                throw new IllegalArgumentException("Class does not implement Plugin interface");
            }
            return (MessagePlugin) instance;
        }
    }

    public static void main(String[] args) throws Exception {
        // 插件 JAR 路径（根据你实际情况替换）
        String jarPath = "D:\\Code\\plugin-demo\\message-demo-classloader\\src\\main\\resources\\jar\\message-aliyun-1.0.0-SNAPSHOT.jar";
        String className = "com.myhexin.demo.plugin.message.impl.AliyunMessagePlugin";

        MessagePlugin plugin = PluginLoader.loadPlugin(jarPath, className);
        System.out.println("Loaded plugin: " + plugin.getName());
        Map<String, String> map = new HashMap<>();
        map.put("phone", "17356535385");
        map.put("content", "验证码：666666");
        plugin.sendMsg(map);
    }
}
